/***********************************
Auth:maohh
Date:2015-09-10
***********************************/
;
(function ($) {
    var itemIndex = 0; //索引值
    var functionalKeyArray = [9, 20, 13, 16, 17, 18, 91, 92, 93, 45, 36, 33, 34, 35, 37, 39, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 144, 19, 145, 40, 38, 27]; //键盘上功能键键值数组
    var ops; //存储变量
    var inputbtn; //键入值
    var valuebtn; //存储值
    var textbtn; //显示值
    $.fn.searchshow = function (options) {
        var defult = {
            width: 200, //控件宽度
            itemnum: 10, //集合条目
            height: 24, //搜索盒子的高度
            minchar: 1, //最小字符串
            datafn: GetData, //加载数据函数
            tffloat: true
        };
        inputbtn = $(this).attr('inputcol');
        valuebtn = $(this).attr('valcol');
        textbtn = $(this).attr('textcol');
        var textDefault = $(this).val();
        ops = $.extend(defult, options);
        var $this = $(this);
        $this.width(ops.width);
        $this.height(ops.height);
        var $autoSearchItemSet = '<div id="autoSearchItemSet"><ul class="menu_v"></ul></div>';
        $this.after($autoSearchItemSet);
        var $autoitemset = $('#autoSearchItemSet');
        $autoitemset.width(ops.width);
        $autoitemset.height(ops.itemnum * ops.height);
        $autoitemset.css('line-height', ops.height + 'px');
        //获取到了焦点
        $this.focusin(function () {
            if ($(this).val() == textDefault)
                $(this).val('');
        });
        //失去了焦点
        $this.focusout(function () {
            if ($(this).val() == '')
                $(this).val(textDefault);
        });
        /*对键盘的操作*/
        $this.keydown(function (e) {
            switch (e.keyCode) {
            case 27: //esc
                $autoitemset.hide(); //要注意显示出来
                break;
            case 38: //↑
                if ($autoitemset.css("display") == "none")
                    return;
                var selectrow = $('.select');
                if (selectrow.length <= 0 || selectrow.nextAll().length == $('li').length - 1) {
                    if (!ops.tffloat)
                        return false;
                    selectrow = $autoitemset.find("li:last");
                } else {
                    selectrow = selectrow.prev();
                }
                $autoitemset.find('li').removeClass('select');
                selectrow.addClass('select');
                var heighttest = selectrow.position();
                if (heighttest.top >= ops.height * (ops.itemnum - 1)) {
                    $autoitemset.scrollTop(heighttest.top);
                } else if (heighttest.top <= 0) {
                    $autoitemset.scrollTop($autoitemset.scrollTop() - ops.height);
                }
                break;
            case 40: //↓
                if ($autoitemset.css("display") == "none")
                    return;
                var selectrow = $('.select');
                if (selectrow.length <= 0 || selectrow.nextAll().length == 0) {
                    if (!ops.tffloat)
                        return false;
                    selectrow = $autoitemset.find("li:first");
                } else {
                    selectrow = selectrow.next();
                }
                $autoitemset.find('li').removeClass('select');
                selectrow.addClass('select');
                var heighttest = selectrow.position();
                if (heighttest.top > (ops.itemnum * ops.height - ops.height)) {
                    $autoitemset.scrollTop($autoitemset.scrollTop() + ops.height);
                } else if (heighttest.top <= 0) {
                    $autoitemset.scrollTop(0);
                }
                break;
            case 13: //回车
                if ($autoitemset.css("display") == "none")
                    return false; //这里必须返回false
                var selectrow = $('.select');
                if (selectrow.length <= 0)
                    return false; //没有选择就没有动作
                else {
                    $(this).text(selectrow.data('jsondata')[valuebtn] + ' ' + selectrow.data('jsondata')[textbtn]);
                    $(this).val(selectrow.data('jsondata')[textbtn]);
                    $autoitemset.hide();
                }
                return false;
            }
        });
        $(this).keyup(function (e) {
            var flag = false;
            for (var i = 0; i < functionalKeyArray.length; i++) {
                if (e.keyCode == functionalKeyArray[i]) {
                    flag = true;
                    break;
                }
            }
            if (flag == false) {
                if ($(this).val().length >= ops.minchar) {
                    var position = $this.position();
                    $autoitemset.css({
                        'visibility': 'visible',
                        'left': position.left,
                        'top': position.top + $this.height
                    });
                    var mes = ops.datafn($this);
                    initItem($(this), mes);
                    $autoitemset.show();
                } else {
                    $autoitemset.hide();
                    $this.val('');
                    $this.text('');
                }
            }
        });
        $(document).click(function () {
            $('li').removeClass('select');
            $autoitemset.hide();
        });
    };
    var initItem = function (obj, mes) {
        var str = '';
        if (mes.length <= 0) {
            $('#autoSearchItemSet ul').html('');
            $('#autoSearchItemSet').css('visibility', 'hidden');
        } else {
            for (var i = 0; i < mes.length; i++) {
                str += '<li><span>' + mes[i][textbtn] + '</span></li>'
            }
            if (mes.length < ops.itemnum)
                $('#autoSearchItemSet').height(mes.length * ops.height);
            else
                $('#autoSearchItemSet').height(ops.height * ops.itemnum);
            $('#autoSearchItemSet ul').html(str);
            $('li').each(function (index) {
                $(this).data('jsondata', mes[index]);
                $(this).bind(
                    'click',
                    function () {
                        obj.text($(this).data('jsondata')[valuebtn] + ' ' + $(this).data('jsondata')[textbtn]);
                        obj.val($(this).data('jsondata')[textbtn]);
                        obj.focus();
                    });
            });
            $('li').each(function () {
                $(this).hover(
                    function () {
                        $('li').removeClass('select');
                        $(this).addClass('select')
                    },
                    function () {}
                );
            });
        };
    };
    var GetData = function (val) {
        var returndata = [];
        if (val.val() != "") {
            $.ajax({
                url: val.attr('datasrc'),
                type: "GET",
                async: false,
                cache: false,
                dataType: "json",
                success: function (data) {
                    var a = data;
                    var str = val.val();
                    var a1 = val.attr("inputcol");
                    str = str.toUpperCase();
                    for (var i in a) {
                        if (a[i][a1].toUpperCase().indexOf(str) != -1)
                            returndata.push(a[i]);
                    }
                },
                Error: function (err) {
                    alert(err);
                }
            });
        }
        return returndata;
    }
})(jQuery);